/*
 Developer: John Archer (john.archer.jpa@gmail.com)
 
 This file is part of VTBuilder.

 VTBuilder is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License.

 VTBuilder is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with VTBuilder.  If not, see <http://www.gnu.org/licenses/>.
 */
package core.tasks;

import core.para.Para;
import core.rb.MB;
import core.rb.r.MR;
import core.tasks.pack.MatchPack;
import gui.processor.Processor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;

public class Match {

    public Match() {
    }

    public MB mb(ArrayList<String> phaseReads, int refLen, HashMap<String, ArrayList<Integer>> hsh, Processor p) throws Exception {
        int size = (phaseReads.size() / Para.TRDS);
        MatchPack[] mp = new MatchPack[Para.TRDS];
        CountDownLatch cdl = new CountDownLatch(Para.TRDS);


        for (int x = 0; x < Para.TRDS; x++) {
            if (x > 0) {
                mp[x] = new MatchPack(
                        cdl,
                        phaseReads.subList(x * size, (x * size + size)),
                        hsh,
                        refLen,
                        null);
            } else {
                mp[x] = new MatchPack(
                        cdl,
                        phaseReads.subList(x * size, (x * size + size)),
                        hsh,
                        refLen,
                        p);
            }
            mp[x].start();
        }
        cdl.await();

        @SuppressWarnings("unchecked")
        ArrayList<MR>[] comb = new ArrayList[refLen];
        for (int s = 0; s < comb.length; s++) {
            comb[s] = new ArrayList<MR>();
        }
        
        //array of MatchPacks
        for (int x = 0; x < mp.length; x++) {
            //for each site of the ref (its an array that contains arraylists)
            for (int s = 0; s < mp[x].pOut.length; s++) {
                //for each iterm in the array list
                for (int r = 0; r < mp[x].pOut[s].size(); r++) {
                    //add it to the total reads at that site S
                    comb[s].add(mp[x].pOut[s].get(r));
                }
            }
        }
       
        MB mb = new MB();
        for (int s = 0; s < comb.length; s++) {
            for (int r = 0; r < comb[s].size(); r++) {
                mb.mrl.add(comb[s].get(r));
            }
        }
        return mb;
    }
}